package com.gopay.scheduler.job;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.gopay.common.constants.proccode.ProcCodeConstants;
import com.gopay.common.constants.trans.Tran01400Step;
import com.gopay.common.domain.acps.AcpsAcctMast;
import com.gopay.common.domain.cps.trans.Tran01400VO;
import com.gopay.common.domain.cps.vo.CPSResponse;
import com.gopay.common.order.dao.CommonQueryDAO;
import com.gopay.common.util.DateUtils;
import com.gopay.scheduler.GopayBaseJob;
import com.gopay.scheduler.common.CallCPSHelper;

public class ReturnProfitToMerchantJob extends GopayBaseJob {
    //日志
    private Logger logger = LoggerFactory.getLogger(ReturnProfitToMerchantJob.class);
            
    /**
     * 公共查询Dao
     */
    @Resource(name = "commonQueryDAO")
    private CommonQueryDAO commonQueryDAO;

    /**
     * 访问CPS辅助类
     */
    @Resource(name = "callCPSHelper")
    private CallCPSHelper callCPSHelper;
    
    @Override
    public void doJobInternal() {
        
        //当前时间
        Date curDate=new Date();
        
        //配合测试
//        curDate=DateUtils.strToDate("20150801", "yyyyMMdd");
     
       
        //当前月
        String curMonth=DateUtils.format(curDate, "yyyyMM");        
        
        //计算上月
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(curDate);
        calendar.add(Calendar.MONTH, -1);
        //上月
        String preMonth=DateUtils.format(calendar.getTime(), "yyyyMM");
        
        //查询商户账户列表
        List<AcpsAcctMast> acctList=queryMerAcct(preMonth,curMonth);
        logger.info("acctList size="+acctList.size());
        
        AcpsAcctMast acct;
        Tran01400VO paramVo;
        CPSResponse response;
        for(int i=0;i<acctList.size();i++){
            acct=acctList.get(i);
            
            paramVo=new Tran01400VO();
            paramVo.setCurBizStep(Tran01400Step.CRON_NEW);
            paramVo.setCustId(acct.getCustId());
            paramVo.setAcctId(acct.getAcctId());
            paramVo.setMonth(preMonth);
            paramVo.setSettleDateBegin(preMonth+"01");
            paramVo.setSettleDateEnd(curMonth+"01");
            
            logger.info("开始第"+i+"个 paramVo="+paramVo);
            try {
                // 调用cps
                response=callCPSHelper.callByVOTicket(paramVo);
                if (!ProcCodeConstants.PROC_CODE_100S1000.equals(response.getRespCode())) {
                    logger.error("------调用cps返回异常  response="+response.getRespCode());
                }
            } catch (Exception e) {
                // 吃掉所有异常
                logger.error("callByVOTicket Error", e);
            }
        }
        
       
    }
    
    /**
     * 查询商户账户列表
     * @param preMonth
     * @param curMonth
     * @return
     */
    private List<AcpsAcctMast> queryMerAcct(String preMonth,String curMonth){
        List<AcpsAcctMast> acctList=new ArrayList<AcpsAcctMast>();
        
        StringBuilder sb = new StringBuilder();
        
        sb.append(" select distinct t.mer_id,t.main_recv_acct ");
        sb.append(" from cps_gen_main_order t ");
        sb.append(" left join ss_acct_solution_rel r on (t.main_recv_acct=r.acct_id and  r.solution_type = 'TPR') ");
        sb.append(" left join ss_trans_profit_dtl d on d.solution_id = r.solution_id ");
        sb.append(" where 1 = 1       ");
        sb.append("   and (d.TRANS_END_DATE is null or d.TRANS_END_DATE>=:preMonth) ");
        sb.append("   and d.TRANS_START_DATE<=:preMonth ");
        sb.append("   and d.TRANS_AUTHORITY=1 ");
        sb.append("   and t.txn_sta_cd=20000 ");
        sb.append("   and t.gopay_int_txn_cd in('00100','01200','01203') ");
        sb.append("   and t.order_stlm_time between ");
        sb.append("      to_timestamp(:preMonthTime, 'yyyymmddHH24miss') and ");
        sb.append("      to_timestamp(:curMonthTime, 'yyyymmddHH24miss') ");
        
        
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("preMonth",preMonth);
        map.put("preMonthTime",preMonth+"01000000");
        map.put("curMonthTime",curMonth+"01000000");
        
        List<Object[]> rsList = commonQueryDAO.findBySql(sb.toString(), map);
        AcpsAcctMast r = null;
        if (rsList != null && rsList.size() > 0) {
            for (Object[] arr : rsList) {
                r = new AcpsAcctMast();                
                r.setCustId((String) arr[0]);
                r.setAcctId((String) arr[1]);
                
                acctList.add(r);
            }
        }
        
        return acctList;
    }

}
